package com.imsprint.lib.observe;

import java.util.Vector;

public class Observable {
    //数据是否变化标志
    private boolean changed = false;
    private final Vector<Observer> observers;

    public Observable() {
        observers = new Vector<>();
    }
    //2.1添加观察者
    private synchronized void addObserver(Observer o) {
        if (o == null)
            throw new NullPointerException();
        if (!observers.contains(o)) {
            observers.add(o);
        }
    }
    //2.2删除观察者
    private synchronized void deleteObserver(Observer o) {
        observers.remove(o);
    }
    //3.1通知所有观察者
    private void notifyObservers() {
        notifyObservers(null);
    }

    private void notifyObservers(Object arg) {
        Observer[] arrLocal;

        synchronized (this) {
            if (!hasChanged())
                return;
            arrLocal = observers.toArray(new Observer[observers.size()]);
            clearChanged();
        }
        for (int i = arrLocal.length-1; i>=0; i--)
            arrLocal[i].onEvent(arg);
    }

    public synchronized void deleteObservers() {
        observers.clear();
    }

    protected synchronized void setChanged() {
        changed = true;
    }

    protected synchronized void clearChanged() {
        changed = false;
    }

    public synchronized boolean hasChanged() {
        return changed;
    }

    public synchronized int countObservers() {
        return observers.size();
    }


    public void post(Object msg){
        setChanged();
        notifyObservers(msg);
    }


    public void register(Observer observer){
        addObserver(observer);
    }

    public void unRegister(Observer observer){
        deleteObserver(observer);
    }
}